//
//  CXMarker.swift
//  CXPack
//
//  Created by 陈警卫 on 2023-12-22.
//

import Foundation
import XcodeKit

class CXMarker {
    
    static func marker(_ invocation: XCSourceEditorCommandInvocation) {
        guard let range = invocation.buffer.selections.firstObject as? XCSourceTextRange else { return }
        let line = range.end.line + 1
        let column = range.end.column
        
        var params: [String] = []
        let code = invocation.buffer.lines[line] as! String
        if code.contains("func") {
            params = extractParams(method: code)
        }
        
        var place = ""
        if column > 1 {
            for _ in 0...(column - 1) {
                place += " "
            }
        }
        var mark = place + "// MARK: <#param#>\n" + place + "/// <#param#>"
        if params.count > 0 {
            mark += "\n"
        }
        for param in params {
            mark += place + "/// " + param + ": <#parma#>\n"
        }
        invocation.buffer.lines.insert(mark, at: line)
    }
    
    static func extractParams(method: String) -> [String] {
        let pattern = "\\b\\w+\\b(?=\\s*:\\s*\\b\\w+\\b)"
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return [] }
        let matches = regex.matches(in: method, options: [], range: NSRange(location: 0, length: method.utf16.count))
        
        return matches.map { match in
            if let range = Range(match.range, in: method) {
                return String(method[range])
            } else {
                return ""
            }
        }
    }
}
